window.addEventListener('load', () => {
  (function () {
    let that

    function Game(map) {
      this.food = new Food()
      this.snake = new Snake()
      this.map = map
      that = this
    }

    Game.prototype.start = function () {
      this.food.render(this.map)
      this.snake.render(this.map)

      // 测试蛇的移动
      // this.snake.move()
      // this.snake.render(this.map)
      // this.snake.move()
      // this.snake.render(this.map)
      // this.snake.move()

      running()
      // 键盘移动
      keyboardMove()
      // 吃食物

    }

    // 蛇的键盘移动
    function keyboardMove() {
      document.addEventListener('keydown', e => {
        switch (e.keyCode) {
          case 37:
            that.snake.facing = 'left'
            break
          case 38:
            that.snake.facing = 'bottom'
            break
          case 39:
            that.snake.facing = 'right'
            break
          case 40:
            that.snake.facing = 'top'
            break
        }
      })
    }

    // 蛇的移动
    function running() {
      let timer = setInterval(() => {
        that.snake.move(that.food, that.map)
        that.snake.render(that.map)

        // 判断碰到边界
        let headerX = that.snake.body[0].x
        let headerY = that.snake.body[0].y
        let maxX = that.map.offsetWidth / that.snake.width
        let maxY = that.map.offsetHeight / that.snake.height
        // 停止计时器
        if (headerX < 0 || headerX >= maxX || headerY < 0 || headerY >= maxY) {
          alert('Game Over')
          clearInterval(timer)
        }
      }, 150);
    }

    // 吃食物 
    // function

    window.Game = Game
  })()
  let map = document.getElementById('map')
  let game = new Game(map)
  game.start()
})